package com.zf.bm.common.core.sys.web;

import com.zf.bm.common.core.log.annotation.SysLog;
import com.zf.bm.common.utils.FileUtil;
import com.zf.bm.common.utils.Result;
import com.zf.bm.common.utils.ResultStatus;
import com.zf.bm.common.web.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
 * 浏览器下载
 */
@Controller
public class DownloadController extends BaseController {
    private static final String CHARSET_UTF_8 = "utf-8";
    private static final String HEADER_FILE_NAME = "filename";
    private static final String FIREFOX_EXE = "Firefox.exe";
    private static final String CHROME_EXE = "chrome.exe";

    @SysLog("下载浏览器")
    @RequestMapping(value = "${adminPath}/download",method = RequestMethod.POST)
    public Result download(HttpServletRequest request, HttpServletResponse response){
        try {
            String type = request.getParameter("type");
            if ("firefox".equals(type)){
                File file = new File("/usr/opt/mc/scripts_v2/Firefox.exe");
                String codedFileName = URLEncoder.encode(FIREFOX_EXE, CHARSET_UTF_8);
                response.setHeader(HEADER_FILE_NAME, new String((codedFileName).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
                response.setHeader("Access-Control-Expose-Headers", FIREFOX_EXE);
                FileUtil.downFileNoReset(file, request, response, FIREFOX_EXE);
            }else {
                File file = new File("/usr/opt/mc/scripts_v2/chrome.exe");
                String codedFileName = URLEncoder.encode(CHROME_EXE, CHARSET_UTF_8);
                response.setHeader(HEADER_FILE_NAME, new String((codedFileName).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
                response.setHeader("Access-Control-Expose-Headers", CHROME_EXE);
                FileUtil.downFileNoReset(file, request, response, CHROME_EXE);
            }
            return new Result(ResultStatus.SUCCESS.getCode(), "下载成功！");
        }catch (Exception e){
            logger.info("下载错误：{}", e);
            return new Result(ResultStatus.FAIL.getCode(),"下载失败");
        }
    }
}
